package com.gitee.hermer.engine.jars.dependent.dsm.client;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.Socket;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.gitee.hermer.boot.jee.commons.log.UtilsContext;
import com.gitee.hermer.engine.jars.dependent.dsm.IEnginePropertiesAware;
import com.gitee.hermer.engine.jars.dependent.dsm.client.config.DsmClientProperties;

@Component
public class SocketClient extends UtilsContext implements IEnginePropertiesAware<DsmClientProperties>{

	@Autowired
	private DsmClientProperties properties;

	public String requestDataSourceInfo(String applicationName, String dataSourceName) throws Exception
	{
		Socket s = null;
		StringBuilder sb = null;
		InputStream in = null;
		OutputStream out = null;
		try
		{
			if (applicationName == null)
			{
				info("method=requestDataSourceInfo,{applicationName=" + applicationName + "},{The socketClient send the applicationName to the socketServer.}");
				return "ERRORAppliName";
			}
			String ip = properties.getDsmServiceIp();
			Integer port = properties.getDsmServicePort();
			info("method=requestDataSourceInfo,{ip=" + ip + ",port=" + port + "},{This is socketClient ip and port.}");
			s = new Socket(ip, port);
			out = s.getOutputStream();
			info("method=requestDataSourceInfo,{applicationName=" + applicationName + "," + "dataSourceName" + "=" + dataSourceName + "},{The socketClient send the information to the socketServer.}");
			out.write(("applicationName=" + applicationName + "&" + "dataSourceName" + "=" + dataSourceName).getBytes());
			in = s.getInputStream();
			byte[] by = new byte[1024];
			int len = in.read(by);
			sb = new StringBuilder(new String(by, 0, len));
		}finally{
			try{
				if(in != null)
					in.close();
			}catch (Exception e) { }
			try{
				if(out != null)
					out.close();
			}catch (Exception e) { }
			try{
				if(s != null)
					s.close();
			}catch (Exception e) { }
		}
		return sb.toString();
	}

	@Override
	public void setProperties(DsmClientProperties properties) {
		this.properties = properties;
	}

}
